package campus.aiit.ssl.manage.modbus;

import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Parse of response by Command & FunctionCode
 *
 * @author ihaokun
 * @date 2019/12/19 9:35
 */
public class Parse {
    // Function Code: 0x03, READ_HOLDING_REGISTERS
    public static boolean ofReadStatus(List<Integer> list) {
        if (list == null||list.isEmpty()) {
            System.out.println("无在线设备，设备日志写入撤销");
            return false;
        }
        // ADU(Read Status Instruction Response) :
        // address(1 byte)+funCode(1 byte)+validLength(1 byte)+data
        // length always is 2
        if (list.get(1) == 131) System.err.println("Error");
        return list.get(4) == 1;  // boolean ? on : off
    }

    public static Integer ofzigbeeStatus(List<Integer> list) {
        if (list.size() == 0) {
            return -1;
        }
        Integer status = list.get(4);
        return status;
    }

    public static Integer ofzigbeeStatusFs(List<Integer> list) {
        if (list.size() == 0) {
            return -1;
        }
        Integer status = list.get(4);
        return status;
    }

    public static int ofReadTemperature(List<Integer> list) {
        if (list.isEmpty()) {
            System.out.println("无在线设备");
            return 0;
        }
        return commonNumeralCalculate(list);
    }

    public static int ofReadElectricConsume(List<Integer> list) {
        if (list.isEmpty()){
            return 0;
        }
        return commonNumeralCalculate(list);
    }

    public static int ofReadVolts(List<Integer> list) {
        if (list.isEmpty()){
            return 0;
        }
        return commonNumeralCalculate(list);
    }

    public static int ofReadAmperes(List<Integer> list) {
        if (list.isEmpty())return 0;
        return commonNumeralCalculate(list);
    }

    private static int commonNumeralCalculate(List<Integer> list) {
        int num = 0;
        for (int i = 0; i < list.get(2); i++) {
            num <<= 8;
            num += list.get(3 + i);
        }
        return num / 10;
//    Integer validLength = list.get(2);
//    StringBuilder builder = new StringBuilder();
//    for (int i = 0; i < validLength; i++) {
//      builder.append(Integer.toHexString(list.get(3 + i)));
//    }
//    return Integer.parseInt(builder.toString(), 16) / 10;

    }


    // Function Code: 0x06, WRITE_SINGLE_REGISTER; 0x10, WRITE_MULTIPLE_REGISTERS
    public static boolean ofWrite(List<Integer> list) {
        // success if bytes is non-null
        System.out.println(list.toString());
        return !list.isEmpty();
    }


    public static boolean ofWriteMultipleRegisters(List<Integer> list) {
        System.out.println(list.toString());
        if (list.get(1) == 144) {
            System.err.println("Error, error code 0x90 = 144 decimal");
            throw new ModBus.ADU.PDU.FunctionCodes.ModBusFunctionCodeException("写策略错误（写多个寄存器错误）");
        }
        return true;
    }


}